#pragma once

class RingBuffer {
public:
    struct HeadInfo {
        HeadInfo();
        int m_size;     //缓存长度
        int m_read;     //读取位置
        int m_write;    //写入位置
    };
public:
    RingBuffer();
    ~RingBuffer();

    RingBuffer(const RingBuffer& buff) {
        copy(buff);
    }

    RingBuffer& operator=(const RingBuffer& buff) {
        copy(buff);
        return *this;
    }

    void init(int size);
    void copy(const RingBuffer& buff);
    void clear();

    inline int space() {
        if (m_head.m_read > m_head.m_write) {
            return m_head.m_read - m_head.m_write;
        } else {
            return m_head.m_size - m_head.m_write + m_head.m_read;
        }
    }

    inline int length() {
        auto curSpace = space();
        if (m_head.m_size >= curSpace) {
            return m_head.m_size - curSpace;
        }
        return 0;
    }

    bool write(const char* src, int size);
    bool read(char* ptr, int& size);

    void peekSize(int size);
    bool peek(char* ptr, int& size);
protected:
    char*       m_data;     //缓存数据
    HeadInfo    m_head;     //读写标记
};
